/**
 * 
 */
package com.tamtamy.jttamobile.parser;

import java.lang.reflect.Field;

import org.json.JSONObject;

import android.util.Log;

import com.tamtamy.jttamobile.data.json.JSONTagList;
import com.tamtamy.jttamobile.utility.JSONUtility;


/**
 * Class injecting properties inside the Object mapping Tamtamy Contents
 * @author mirko
 *
 */
public class PropertyInjector {

	@SuppressWarnings("unused")
	private static final String TAG = "PropertyInjector";
	/**
	 * fill the properties using field name for retrieve JSON element
	 * 
	 * @param anObject the object to populate
	 * @param jsonObject the JSONObject to parse
	 */
	public static void populateObject(Object anObject, JSONObject jsonObject){
		Class<?> c = anObject.getClass();
		while( c!= null && !Object.class.equals(c)){
			for (Field field : c.getDeclaredFields() ) {
	    		String name = field.getName();
	    		boolean accessible = field.isAccessible();
	    		Object value = null;
	    		if(jsonObject.has(name) &&!jsonObject.isNull(name)){
	    			try{
	    				if(field.getType().isAssignableFrom(java.util.Date.class)){
	    					value = JSONUtility.getDate(jsonObject, name);
	    				}else if(field.getType().isAssignableFrom(java.util.ArrayList.class)){
	    					value = JSONUtility.getStringList(jsonObject, name);
	    				}else if(field.getType().isAssignableFrom(boolean.class)) {
	    					value = jsonObject.getBoolean(name);
	    				}else if(field.getType().isAssignableFrom(int.class)) {
	    					value = jsonObject.getInt(name);
	    				}else if(field.getType().isAssignableFrom(long.class)) {
	    					value = jsonObject.getLong(name);
	    				}else if(field.getType().isAssignableFrom(double.class)) {
	    					value = jsonObject.getDouble(name);
	    				}else if(field.getType().isAssignableFrom(String.class)) {
	    					value = jsonObject.getString(name);
	    				}else if(field.getType().isAssignableFrom(com.tamtamy.jttamobile.data.TagList.class)){
	    					value = JSONTagList.getTagsListFromJSONArray(jsonObject.getJSONArray(name));
	    				}else {
	    					value = jsonObject.get(name);
	    				}
		    			field.setAccessible(true);
		    			field.set(anObject, value);
		    			field.setAccessible(accessible);
	    			}catch(Exception e){
	    				Log.e(anObject.getClass().getSimpleName(),"Error populate field ["+name+"]",e);
	    			}
	    		}
	    	}
			c = c.getSuperclass();
		}
	}
	
}
